package xcmg.device.web.logistics;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.logistics.SendBillService;
import xcmg.device.service.vo.logistics.SendBillAddVO;
import xcmg.device.service.vo.logistics.SendBillVO;
import xcmg.device.service.warehouse.CommonService;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@RestController
@RequestMapping("/sendBill")
public class SendBillController extends BasicController {

    @Autowired
    private SendBillService sendBillService;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private CommonService commonService;

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult list(@RequestBody SearchCommonVO<SendBillVO> condition)throws Exception{
        SendBillVO sendBillVO = condition.getFilters();
        String orgId = getOrgId();
        sendBillVO.setOrgId(orgId);
        List<String> dealerOrgIds = companyDealerMapper.findDealerOrgIds(sendBillVO.getOrgId());
        if(dealerOrgIds == null){
            dealerOrgIds = new ArrayList<>();
        }
        dealerOrgIds.add(sendBillVO.getOrgId());
        sendBillVO.setDealerOrgIds(new ArrayList<>(new HashSet<>(dealerOrgIds)));
        //处理销售组织筛选
        processSaleCodeList(sendBillVO,orgId,getDeptId());
        condition.setFilters(sendBillVO);
        PageCommonVO pageCommonVO = sendBillService.list(condition, orgId);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    private void processSaleCodeList(SendBillVO sendBillVO, String orgId, String deptId) {
        boolean isYn = commonService.checkIsYnOrgId(orgId);
        if (isYn) {
            sendBillVO.setSalesCodeList(commonService.getSalesCodes(deptId));
        }
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult add(@RequestBody SendBillAddVO sendBillAddVO)throws Exception{
        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        sendBillVO.setCreateId(getUserId());
        sendBillVO.setCreateName(getUserName());
        sendBillAddVO.setHeaderInfo(sendBillVO);
        try {
            return actionResult(sendBillService.add(sendBillAddVO, false));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/item",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult item(String id) throws Exception{
        return actionValueResult(sendBillService.item(id,getOrgId()));
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult update(@RequestBody SendBillAddVO sendBillAddVO)throws Exception{
        try {
            return actionResult(sendBillService.update(sendBillAddVO, false));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/submit",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult submit(@RequestBody SendBillAddVO sendBillAddVO)throws Exception{
        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        sendBillVO.setCreateId(getUserId());
        sendBillVO.setCreateName(getUserName());
        sendBillAddVO.setHeaderInfo(sendBillVO);
        try {
            ErrorCode errorCode;
            if (sendBillVO.getId() == null){
                errorCode = sendBillService.add(sendBillAddVO, true);
            } else {
                errorCode = sendBillService.update(sendBillAddVO, true);
            }
            return actionResult(errorCode);
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/updateIsDelivery",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult updateIsDelivery(@RequestBody SendBillVO sendBillVO)throws Exception{
        try {
            return actionResult(sendBillService.updateIsDelivery(sendBillVO.getId(), getOrgId(), getUserId()));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/sign",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult sign(@RequestBody SendBillAddVO sendBillAddVO)throws Exception{
        try {
            return actionResult(sendBillService.sign(sendBillAddVO, getUserName(), getUserId(), getOrgId()));
        }catch (Exception e){
            LogHelper.monitor(getExceptionAllinformation(e));
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/generateOrder",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult generateOrder(@RequestBody SendBillVO sendBillVO)throws Exception{
        try {
            return actionResult(sendBillService.generateOrder(sendBillVO.getId(), getOrgId()));
        }catch (Exception e){
            LogHelper.monitor(getExceptionAllinformation(e));
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult remove(@RequestBody String[] ids)throws Exception{
        if(ids==null||ids.length==0){
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            return actionResult(sendBillService.delete(Arrays.asList(ids)));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }


    @RequestMapping(value = "/export",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void export( String[] ids)throws Exception {
        sendBillService.export(Arrays.asList(ids));
    }

    @RequestMapping(value = "/exportAll",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void exportAll(SendBillVO condition)throws Exception {
        String orgId=getOrgId();
        condition.setOrgId(orgId);
        List<String> dealerOrgIds = companyDealerMapper.findDealerOrgIds(condition.getOrgId());
        if(dealerOrgIds == null){
            dealerOrgIds = new ArrayList<>();
        }
        dealerOrgIds.add(condition.getOrgId());
        condition.setDealerOrgIds(dealerOrgIds);
        //处理销售组织筛选
        processSaleCodeList(condition,orgId,getDeptId());
        sendBillService.exportAll(condition);
    }

//    @RequestMapping(value = "/sapPost", method = RequestMethod.POST)
//    @ApiOperation(value = "调用采购凭证收货接口")
//    @FastMappingInfo(needLogin = true)
//    public ActionResult sapPost(@RequestBody SendBillDetailVO condition) {
//        ErrorCode errorCode;
//        try {
//            errorCode = sendBillService.sapPost(condition.getId(), getOrgId());
//        } catch (Exception e) {
//            LogHelper.monitor(e.getMessage());
//            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
//        }
//        return actionResult(errorCode);
//    }

    @RequestMapping(value = "/syncSettlementPrice",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult syncSettlementPrice(@RequestBody SendBillVO sendBillVO)throws Exception{
        try {
            return actionResult(sendBillService.syncSettlementPrice(sendBillVO.getId(), getOrgId()));
        }catch (Exception e){
            LogHelper.monitor(getExceptionAllinformation(e));
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }
    
//    @RequestMapping(value = "/pullErpSendBillInfos",method = RequestMethod.POST)
//    @ApiOperation(value = "手动拉取送货单信息")
//    @FastMappingInfo(needLogin = true)
//    public ActionResult pullErpSendBillInfos(@RequestBody SendBillPullCondition condition) throws Exception {
//    	sendBillService.setPullErpSendBillRecord();
//    	sendBillService.manualPullSendInfos(condition);
//    	return actionResult(ErrorCode.Success);
//    }
//
//    @RequestMapping(value = "/pullBlInfos",method = RequestMethod.POST)
//    @ApiOperation(value = "手动拉取送货单信息")
//    public ActionResult pullBlInfos(@RequestBody SendBillPullCondition condition) throws Exception {
//    	sendBillService.setPullErpBlRecord();
//    	sendBillService.manualPullBlInfos(condition);
//    	return actionResult(ErrorCode.Success);
//    }

    @RequestMapping(value = "/updateArrivalDate",method = RequestMethod.GET)
    @ApiOperation(value = "更新送货单到货日期")
    @FastMappingInfo(needLogin = true)
    public ActionResult updateArrivalDate(String id, String arrivalDate) throws Exception{
        if (StringUtils.isBlank(id) || StringUtils.isBlank(arrivalDate)) {
            throw new Exception("主键或者时间不能为空");
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return actionResult(sendBillService.updateArrivalDate(id, sdf.parse(arrivalDate)));
        }catch (Exception e){
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
    }

    private String getExceptionAllinformation(Exception ex){
        String sOut = ex.getMessage()+"\r\n";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
    }
}
